package org.whuims.web.paragraph;

import org.apache.shiro.SecurityUtils;
import org.elasticsearch.common.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;
import org.whuims.entity.Document;
import org.whuims.entity.Paragraph;
import org.whuims.entity.vo.ParagraphVo;
import org.whuims.service.account.ShiroDbRealm;
import org.whuims.service.document.DocumentService;
import org.whuims.service.paragraph.ParagraphService;
import org.whuims.service.paragraph.ParagraphSolrService;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by Qikai on 2016/11/7.
 */
@Controller
@RequestMapping(value = "/para")
public class ParagraphController {

    private static final String PAGE_SIZE = "10";
    @Autowired
    private ParagraphService paragraphService;
    @Autowired
    private ParagraphSolrService paragraphSolrService;
    @Autowired
    private DocumentService documentService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                       @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model,
                       ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page<Paragraph> paras = paragraphService.getParagraphList(searchParams, pageNumber, pageSize, null);
        model.addAttribute("paras", paras);
        model.addAttribute("sortType", "auto");
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "para/paralist";
    }

    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public String detail(@PathVariable("id") Long id, Model model) {
        Paragraph para = paragraphService.getParagraph(id);
        long docId = para.getDocumentId();
        Document document = documentService.getDocument(docId);
        String exists = null;
        if (document != null) {
            if (!Strings.isNullOrEmpty(document.getLocation())) {
                exists = "true";
            }
            model.addAttribute("doc", document);
            model.addAttribute("docType", document.getDocType());
        }
        model.addAttribute("para", para);
        model.addAttribute("exists", exists);
        return "para/paradetail";
    }

    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") Long id, Model model) {
        paragraphService.delete(id);
        paragraphSolrService.delete(String.valueOf(id));
        return "redirect:/para/list";
    }

//    @RequestMapping(value = "create", method = RequestMethod.GET)
//    public String createForm(Model model) {
//        model.addAttribute("para", new Paragraph());
//        model.addAttribute("action", "create");
//        return "para/paraedit";
//    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable("id") Long id, Model model) {
        Paragraph para = paragraphService.getParagraph(id);
        model.addAttribute("para", para);
        return "para/paraedit";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("paragraph") Paragraph paragraph, RedirectAttributes redirectAttributes) {
        paragraphService.save(paragraph);
        redirectAttributes.addFlashAttribute("message", "编辑标准信息成功");
        return "redirect:list";
    }

    @RequestMapping(value = "search", method = RequestMethod.GET)
    public String search(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                         @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model,
                         ServletRequest request) {
        String keyword = request.getParameter("keyword");
        keyword = keyword == null ? "*" : keyword;
        Page<Paragraph> paras = paragraphSolrService.findByTemplate(new PageRequest(pageNumber - 1, pageSize), keyword);
        model.addAttribute("paras", paras);
        model.addAttribute("sortType", "auto");
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("keyword", keyword);
        model.addAttribute("total", paras.getTotalElements());
        return "para/search_result_simple";
    }

    @RequestMapping(value = "doc", method = RequestMethod.GET)
    public String doc(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                      @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model,
                      ServletRequest request) {
        String docIdStr = request.getParameter("docId");
        ParagraphVo paragraphVo = new ParagraphVo();
        paragraphVo.setDocumentId(Long.parseLong(docIdStr));
        Page<Paragraph> paras = paragraphSolrService.findByTemplate(new PageRequest(pageNumber - 1, pageSize), paragraphVo);
        model.addAttribute("paras", paras);
        model.addAttribute("sortType", "auto");
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("docId", docIdStr);
        model.addAttribute("total", paras.getTotalElements());
        return "para/search_result_simple";
    }


    @ModelAttribute
    public void getParagraph(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
        if (id != -1) {
            model.addAttribute("paragraph", paragraphService.getParagraph(id));
        }
    }

    @RequestMapping(value = "searchentry", method = RequestMethod.GET)
    public String simpleSearch() {
        return "para/search";
    }

    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }

    private String getCurrentUserName() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null)
            return null;
        else return user.loginName;
    }
}
